package cn.dms.equipment.action;

import java.io.File;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import cn.dms.equipment.model.Borrow;
import cn.dms.equipment.model.Equipment;
import cn.dms.equipment.model.OutRecordsView;
import cn.dms.equipment.model.Output;
import cn.dms.equipment.model.Parts;
import cn.dms.equipment.model.RepairRecordsView;
import cn.dms.equipment.model.Repairs;
import cn.dms.equipment.service.BorrowService;
import cn.dms.equipment.service.EquipmentService;
import cn.dms.equipment.service.OutRecordsViewService;
import cn.dms.equipment.service.OutputService;
import cn.dms.equipment.service.PartsService;
import cn.dms.equipment.service.RepairRecordsViewService;
import cn.dms.equipment.service.RepairsService;
import cn.dms.system.model.Department;
import cn.dms.system.service.DepartmentService;
import cn.hhit.common.action.CommonAction;
import cn.hhit.common.pagination.Page;
import cn.hhit.common.util.ExcelHelper;
import cn.hhit.common.util.HssfExcelHelper;
import cn.hhit.common.util.StringUtil;
import cn.hhit.system.model.TreeModel;

@SuppressWarnings("rawtypes")
public class EquipmentAction extends CommonAction {
	private static final long serialVersionUID = 1L;

	@Autowired
	@Qualifier("EquipmentService")
	private EquipmentService equipmentService;

	@Autowired
	@Qualifier("DepartmentService")
	private DepartmentService departmentService;

	@Autowired
	@Qualifier("PartsService")
	private PartsService partsService;

	@Autowired
	@Qualifier("OutRecordsViewService")
	private OutRecordsViewService outRecordsViewService;

	@Autowired
	@Qualifier("OutputService")
	private OutputService outputService;

	@Autowired
	@Qualifier("BorrowService")
	private BorrowService borrowService;

	@Autowired
	@Qualifier("RepairRecordsViewService")
	private RepairRecordsViewService repairRecordsViewService;

	@Autowired
	@Qualifier("RepairsService")
	private RepairsService repairsService;

	public Equipment equipment;
	public Parts parts;
	public Output output;
	public OutRecordsView outRecordsView;
	public RepairRecordsView repairRecordsView;
	public int currentId;
	public String dno;
	public int eid;
	public int pid;
	public Integer deptId;
	public int[] jsonString;
	public String state;
	public Date returndate;
	public String mark;
	public boolean belong;
	public boolean equipquery;
	public String outputmark;

	public String showEquipments() {
		return "showequipment";
	}

	public String showParts() {
		return "showparts";
	}

	public String showPartsOut() {
		return "showpartsout";
	}

	public String showOutputs() {
		return "output";
	}

	public String showMaintains() {
		return "maintains";
	}

	public String borrowParts() {
		return "borrowparts";
	}

	public String showRecycles() {
		return "recycles";
	}

	public String showQuery() {
		return "query";
	}

	public String showEquipment() {
		return "equipments";
	}

	public String importEquipment() {
		return "equipments";
	}

	public void clearEquipment() {
		equipmentService.delByParams(" where state='报废'");
		writeStringToClient(response, "操作成功", true);
	}

	public void returnToDamaged() {
		if (jsonString != null && jsonString.length != 0) {
			for (int i = 0; i < jsonString.length; i++) {
				equipmentService.update(" set state=? where id=?", state, jsonString[i]);
			}
		}
		writeStringToClient(response, "操作成功", true);
	}

	public void returnBackEquipment() {
		Output out = outputService.get(currentId);
		Integer eid = out.getEid();
		equipmentService.update(" set state=? where id=?", "在库", eid);
		outputService.update(" set returndate=? ,mark=?, state=? where id=?", returndate, outputmark, "已归还", currentId);
		writeStringToClient(response, "归还成功", true);
	}

	public void returnBackRepairedEquipment() {
		Repairs repair = repairsService.get(currentId);
		Integer eid = repair.getEid();
		if (state.equals("报废")) {
			equipmentService.update(" set state=?,damagedate=? where id=?", "报废", returndate, eid);
		} else if (state.equals("已维护")) {
			equipmentService.update(" set state=?,lastinput=? where id=?", "在库", returndate, eid);
		}
		repairsService.update(" set returndate=? , state=?,repairmark=? where id=?", returndate, state, mark, currentId);

		writeStringToClient(response, "归还成功", true);
	}

	public void downloadEquipmentsToExcel() throws Exception {
		List<Equipment> equipments = equipmentService.listAll();
		String[] titles = new String[] { "设备编号", "设备名称", "状态", "归属部门", "品牌", "型号", "规格", "重量", "入库时间", "使用年限（开始）", "使用年限（结束）", "出库时间", "损坏时间", "维护时间", "报废时间" };
		String[] fieldNames = new String[] { "dno", "name", "state", "department", "brand", "model", "standard", "weight", "lastinput", "start", "end", "outputdate", "damagedate", "repairdate",
				"scapdate" };
		response.setContentType("multipart/form-data");
		setFileDownloadHeader(request, response, fileFileName + ".xls");
		OutputStream out = response.getOutputStream();
		ExcelHelper eh = HssfExcelHelper.getInstance(new File(""));
		eh.writeExcel(Equipment.class, equipments, fieldNames, titles, out);
	}

	public void downloadPartsToExcel() throws Exception {
		List<Parts> parts = partsService.listAll();
		String[] titles = new String[] { "设备编号", "设备名称", "状态", "归属部门", "品牌", "型号", "规格", "重量", "入库时间", "使用年限（开始）", "使用年限（结束）", "出库时间", "损坏时间", "维护时间", "报废时间" };
		String[] fieldNames = new String[] { "pno", "name", "state", "department", "brand", "model", "standard", "weight", "lastinput", "start", "end", "outputdate", "damagedate", "repairdate",
				"scapdate" };
		response.setContentType("multipart/form-data");
		setFileDownloadHeader(request, response, fileFileName + ".xls");
		OutputStream out = response.getOutputStream();
		ExcelHelper eh = HssfExcelHelper.getInstance(new File(""));
		eh.writeExcel(Parts.class, parts, fieldNames, titles, out);
	}

	public void addPartsToEquipment() {
		if (jsonString != null && jsonString.length != 0) {
			for (int i = 0; i < jsonString.length; i++) {
				Borrow b = borrowService.getUnique(" where eid=? and pid=?", eid, jsonString[i]);
				if (b == null) {
					Borrow borrow = new Borrow();
					borrow.setEid(eid);
					borrow.setPid(jsonString[i]);
					borrow.setBorrowdate(new Date());
					borrowService.saveOrUpdate(borrow);
				}
			}
		}
		writeStringToClient(response, "操作成功", true);
	}

	public void editEquipment() {
		equipmentService.saveOrUpdate(equipment);

		if ("维护中".equals(equipment.getState()) || "已维护".equals(equipment.getState()) || "损坏，待维护".equals(equipment.getState())) {
			Repairs repair = new Repairs();
			repair.setEid(equipment.getId());
			repair.setMark("需要入库人完善损坏/维护信息");
			repair.setCreatedate(new Date());
			repairsService.saveOrUpdate(repair);
		}

		writeObjectToClient(response, equipment, true);
	}

	public void editParts() {
		partsService.saveOrUpdate(parts);
		writeObjectToClient(response, parts, true);
	}

	public void editOutput() {
		Output output = new Output();
		output.setId(outRecordsView.getId());
		output.setEid(outRecordsView.getEid());
		output.setMark(outRecordsView.getMark());
		output.setOutdate(outRecordsView.getOutdate());
		output.setOutpeople(outRecordsView.getOutpeople());
		output.setReturndate(outRecordsView.getReturndate());
		output.setUsepeople(outRecordsView.getUsepeople());
		output.setState("出库");
		outputService.saveOrUpdate(output);
		Equipment equipment = equipmentService.get(outRecordsView.getEid());
		equipment.setState("出库");
		equipment.setOutputdate(outRecordsView.getOutdate());
		equipmentService.saveOrUpdate(equipment);
		writeObjectToClient(response, output, true);
	}

	public void editRepair() {
		Repairs repair = new Repairs();
		repair.setAssign(repairRecordsView.getAssign());
		repair.setEid(repairRecordsView.getEid());
		repair.setMark(repairRecordsView.getMark());
		repair.setRepairdate(repairRecordsView.getRepairdate());
		repair.setRepairman(repairRecordsView.getRepairman());
		repair.setRepairmark(repairRecordsView.getRepairmark());
		repair.setReturndate(repairRecordsView.getReturndate());
		repair.setState("维护中");
		repair.setId(repairRecordsView.getId());
		repairsService.saveOrUpdate(repair);
		Equipment equipment = equipmentService.get(repairRecordsView.getEid());
		if (repairRecordsView.getReturndate() != null) {
			equipment.setState("在库");
		} else {
			// if ("是".equals(repairRecordsView.getAssign())) {
			// equipment.setState("维护中");
			// } else {
			equipment.setState("维护中");
			// }
		}
		equipment.setRepairdate(repairRecordsView.getRepairdate());
		equipmentService.saveOrUpdate(equipment);
		writeObjectToClient(response, output, true);
	}

	public void findEquipment() {
		Equipment equipment = equipmentService.get(currentId);
		writeObjectToClient(response, equipment, true);
	}

	public void findEquipmentByHql() {
		Equipment equipment = equipmentService.getUnique("where dno=?", dno);
		writeObjectToClient(response, equipment, true);
	}

	public void findParts() {
		Parts parts = partsService.get(currentId);
		writeObjectToClient(response, parts, true);
	}

	public void findOutRecordsView() {
		OutRecordsView outRecordsView = outRecordsViewService.get(currentId);
		writeObjectToClient(response, outRecordsView, true);
	}

	public void findRepairRecordsView() {
		RepairRecordsView repairRecordsView = repairRecordsViewService.get(currentId);
		writeObjectToClient(response, repairRecordsView, true);
	}

	public void equipmentListAll() {
		if (belong) {
			List<Equipment> equipments = new ArrayList<Equipment>();
			List<Borrow> borrows = borrowService.listByParams("where pid=?", pid);
			if (borrows != null) {
				for (Borrow borrow : borrows) {
					Equipment equipment = equipmentService.get(borrow.getEid());
					if (equipment != null) {
						equipments.add(equipment);
					}
				}
			}
			writeListToClient(response, equipments, true);
		} else {
			StringBuffer filter = new StringBuffer(" where 1=1");
			String queryString = StringUtil.buildFuzzySearch(query, queryField, queryValue);
			filter.append(queryString);
			if (state != null) {
				filter.append("and state='" + state + "' ");
			} else {
				if (equipquery) {

				} else {
					filter.append("and state!='报废'");
				}
			}
			Page<Equipment> equipments = equipmentService.listByParams(page, limit, filter.toString());
			writePageListToClient(response, equipments);
		}
	}

	public void partsListAll() {
		if (currentId != 0) {
			List<Parts> parts = partsService.listByParams("where did=?", currentId);
			List<Borrow> borrows = borrowService.listByParams("where eid=?", currentId);
			if (borrows != null) {
				for (Borrow borrow : borrows) {
					Parts part = partsService.get(borrow.getPid());
					if (part != null) {
						parts.add(part);
					}
				}
			}
			writeListToClient(response, parts, true);
		} else {
			StringBuffer filter = new StringBuffer(" where 1=1");
			String queryString = StringUtil.buildFuzzySearch(query, queryField, queryValue);
			filter.append(queryString);
			Page<Parts> parts = partsService.listByParams(page, limit, filter.toString());
			writePageListToClient(response, parts);
		}
	}

	public void outRecordsListAll() {
		StringBuffer filter = new StringBuffer(" where 1=1");
		if (eid != 0) {
			filter.append(" and eid=" + eid);
		}
		String queryString = StringUtil.buildFuzzySearch(query, queryField, queryValue);
		filter.append(queryString);
		filter.append(" order by outdate desc");
		Page<OutRecordsView> outRecordsViews = outRecordsViewService.listByParams(page, limit, filter.toString());
		writePageListToClient(response, outRecordsViews);
	}

	public void repairRecordsListAll() {
		StringBuffer filter = new StringBuffer(" where 1=1");
		if (eid != 0) {
			filter.append(" and eid=" + eid);
		}
		String queryString = StringUtil.buildFuzzySearch(query, queryField, queryValue);
		filter.append(queryString);
		filter.append(" order by repairdate desc");
		Page<RepairRecordsView> repairRecordsViews = repairRecordsViewService.listByParams(page, limit, filter.toString());
		writePageListToClient(response, repairRecordsViews);
	}

	public void equipmentTreeList() {

		List<TreeModel> treelist = new ArrayList<TreeModel>();
		if (deptId == -1) {
			List<Department> dmlist = departmentService.listByParams(" order by deptname");
			for (Department dm : dmlist) {
				TreeModel node = new TreeModel();
				node.setId(dm.getId().toString());
				node.setSortIndex(dm.getId() * -1);
				node.setText(dm.getDeptname());
				node.setIconCls("contract");
				node.setLeaf(false);
				treelist.add(node);
			}
		} else {
			List<Equipment> emList = new ArrayList<Equipment>();
			emList = equipmentService.listByParams("where departmentid=? order by name", deptId);
			if (!emList.isEmpty()) {
				for (Equipment em : emList) {
					if (em != null) {
						TreeModel node = new TreeModel();
						node.setId(StringUtil.parseNULLtoString(em.getId()) + "equipment");
						node.setLeaf(true);
						node.setSortIndex(em.getId());
						node.setText(em.getName());
						node.setIconCls("camera");
						treelist.add(node);
					}
				}
			}

		}
		writeListToClient(response, treelist, true);

		// List<Equipment> equipments = equipmentService.listAll();
		// List<TreeModel> trees = new ArrayList<TreeModel>();
		// if (equipments != null && equipments.size() > 0) {
		// for (Equipment equipment : equipments) {
		//
		// }
		// }
		// writeListToClient(response, trees, true);
	}

	public void removePartsFromEuipment() {
		if (delIds != null) {
			for (int i = 0; i < delIds.length; i++) {
				List<Borrow> borrows = borrowService.listByParams(" where eid=? and pid=?", eid, delIds[i]);
				if (borrows != null && !borrows.isEmpty()) {
					borrowService.delByParams(" where eid=? and pid=?", eid, delIds[i]);
				} else {
					partsService.delByParams(" where id=?", delIds[i]);
				}
			}
		}
		writeResultToClient(response, true);
	}

	public Equipment getEquipment() {
		return equipment;
	}

	public void setEquipment(Equipment equipment) {
		this.equipment = equipment;
	}

	public Parts getParts() {
		return parts;
	}

	public void setParts(Parts parts) {
		this.parts = parts;
	}

	public int getCurrentId() {
		return currentId;
	}

	public void setCurrentId(int currentId) {
		this.currentId = currentId;
	}

	public String getDno() {
		return dno;
	}

	public void setDno(String dno) {
		this.dno = dno;
	}

	public Output getOutput() {
		return output;
	}

	public void setOutput(Output output) {
		this.output = output;
	}

	public OutRecordsView getOutRecordsView() {
		return outRecordsView;
	}

	public void setOutRecordsView(OutRecordsView outRecordsView) {
		this.outRecordsView = outRecordsView;
	}

	public int getEid() {
		return eid;
	}

	public void setEid(int eid) {
		this.eid = eid;
	}

	public int getPid() {
		return pid;
	}

	public void setPid(int pid) {
		this.pid = pid;
	}

	public int[] getJsonString() {
		return jsonString;
	}

	public void setJsonString(int[] jsonString) {
		this.jsonString = jsonString;
	}

	public RepairRecordsView getRepairRecordsView() {
		return repairRecordsView;
	}

	public void setRepairRecordsView(RepairRecordsView repairRecordsView) {
		this.repairRecordsView = repairRecordsView;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public Integer getDeptId() {
		return deptId;
	}

	public void setDeptId(Integer deptId) {
		this.deptId = deptId;
	}

	public boolean isBelong() {
		return belong;
	}

	public void setBelong(boolean belong) {
		this.belong = belong;
	}

	public Date getReturndate() {
		return returndate;
	}

	public void setReturndate(Date returndate) {
		this.returndate = returndate;
	}

	public String getMark() {
		return mark;
	}

	public void setMark(String mark) {
		this.mark = mark;
	}

	public boolean isEquipquery() {
		return equipquery;
	}

	public void setEquipquery(boolean equipquery) {
		this.equipquery = equipquery;
	}

	public String getOutputmark() {
		return outputmark;
	}

	public void setOutputmark(String outputmark) {
		this.outputmark = outputmark;
	}

}
